#!/usr/bin/python

# hostbuilder - Tools for DNS zonefile administration
# Copyright (c) 2010 Crown copyright
# 
# This file is part of hostbuilder.
# 
# hostbuilder is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# hostbuilder is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with hostbuilder.  If not, see <http://www.gnu.org/licenses/>.


"""Generate a tab-completion file from hosts.yaml.

This is an idealised tab-completion file where multiple aliases that would
block tab-completion because they share a common prefix are omitted. For
example, a machine that is available both as

red.example.com

and 

red.staging.example.com

would only be output under the former name, so that tab completion would not
simply output

red.

and then wait for the user to narrow down the selection.
"""

import yaml

SEARCH = 'example.com'

hosts = yaml.load(open('hosts.yaml'))


# build a list of name -> cname pairs
names = []
def add_name(name, host):
    search = '.' + SEARCH
    if name.endswith(search):
        short = name[:-len(search)]
        names.append((short, host))
    names.append((name, host))


for h, params in hosts.items():
    add_name(h, h)
    for alias in params.get('aliases', []):
        add_name(alias, h)

# sort by name
names.sort()

# only output the first in a run of adjacent names that refer to the same host
last = None
for name, cname in names:
    if cname != last:
        print name
    last = cname
